package com.guigu.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
 * 短信发送工具类
 *    第一个参数  工具类里定义的短信模板的  模版CODE
 *    第二个参数  要发送的手机号
 *    第三个参数  短信模板里的 ${code}
 *    SMSUtils.sendShortMessage(VALIDATE_CODE,"15340809018","1234");
 */
public class SMSUtils {
    // 短信模板CODE
    public static final String LOGIN_VALIDATE_CODE = "SMS_480485113";  // 手机号登录验证
    public static final String REGISTERED_VALIDATE_CODE = "SMS_480115399"; // 手机号注册验证码
    public static final String ORDER_NOTICE = "SMS_314720492";  // 验证码短信


    // 阿里云短信服务配置
    private static final String PRODUCT = "Dysmsapi"; // 短信API产品名称
    private static final String DOMAIN = "dysmsapi.aliyuncs.com"; // 短信API产品域名
    private static final String REGION = "cn-hangzhou"; // 区域
    private static final String SIGN_NAME = "xx优选"; // 短信签名

    // 超时时间（单位：毫秒）
    private static final String CONNECT_TIMEOUT = "10000";
    private static final String READ_TIMEOUT = "10000";

    // 环境变量中的AK
    private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

    /**
     * 发送短信
     *
     * @param templateCode  短信模板CODE
     * @param phoneNumbers  手机号
     * @param param         模板参数（如验证码）
     * @return 是否发送成功
     * @throws ClientException 阿里云客户端异常
     */
    public static boolean sendShortMessage(String templateCode, String phoneNumbers, String param) throws ClientException {
        // 设置超时时间
        setTimeouts();

        // 初始化客户端
        IAcsClient acsClient = initAcsClient();

        // 组装请求对象
        SendSmsRequest request = buildSendSmsRequest(templateCode, phoneNumbers, param);

        // 发送请求并处理响应
        return handleSendSmsResponse(acsClient.getAcsResponse(request));
    }

    /**
     * 设置超时时间
     */
    private static void setTimeouts() {
        System.setProperty("sun.net.client.defaultConnectTimeout", CONNECT_TIMEOUT);
        System.setProperty("sun.net.client.defaultReadTimeout", READ_TIMEOUT);
    }

    /**
     * 初始化阿里云客户端
     */
    private static IAcsClient initAcsClient() throws ClientException {
        IClientProfile profile = DefaultProfile.getProfile(REGION, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        DefaultProfile.addEndpoint(REGION, REGION, PRODUCT, DOMAIN);
        return new DefaultAcsClient(profile);
    }

    /**
     * 组装短信发送请求
     */
    private static SendSmsRequest buildSendSmsRequest(String templateCode, String phoneNumbers, String param) {
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(phoneNumbers);
        request.setSignName(SIGN_NAME);
        request.setTemplateCode(templateCode);
        request.setTemplateParam("{\"code\":\"" + param + "\"}");
        return request;
    }

    /**
     * 处理短信发送响应
     */
    private static boolean handleSendSmsResponse(SendSmsResponse response) {
        if ("OK".equals(response.getCode())) {
            System.out.println("短信发送成功");
            return true;
        } else {
            System.err.println("短信发送失败，错误码：" + response.getCode());
            return false;
        }
    }
}
